<script type="text/javascript">
	$(document).ready(function () {
        var group_task = "CREATE";
        var btn_group_task = "";
		var gridExpandVar = 0;
		var formExpandVar = 0;
        var editrow = -1;
		
		var navbar = $("#jqxNavigationBar");
		navbar.jqxNavigationBar({ width: '100%', height: 420, sizeMode: 'auto', theme: theme });
		
		/* START DATA */
		// prepare the data
		var source =
		{
			datatype: "json",
			datafields: [
				{ name: 'group_id' },
				{ name: 'group_name' },
				{ name: 'group_desc'},
				{ name: 'group_active'}
			],
			id: 'group_id',
			url: 'index.php?c=c_group&m=group_list',
			root: 'data'
		};
		var dataAdapter = new $.jqx.dataAdapter(source);


		var initrowdetails = function (index, parentElement, gridElement) {
            var tabsdiv = null;
            var information = null;
            //var notes = null;
            tabsdiv = $($(parentElement).children()[0]);

            var rows = $("#jqxgrid").jqxGrid('getrows');

            if (tabsdiv != null) {
                information = $.find('.information' + index);
                //notes = $.find('.notes' + index);

                var container = $('<div style="margin: 5px;"></div>');
                container.appendTo($(information));
                var photocolumn = $('<div style="float: left; width: 15%;"></div>');
                var leftcolumn = $('<div style="float: left; width: 45%;"></div>');
                var rightcolumn = $('<div style="float: left; width: 40%;"></div>');
                container.append(photocolumn);
                container.append(leftcolumn);
                container.append(rightcolumn);

                var datarecord = rows[index];

                var photo = $("<div class='jqx-rc-all' style='margin: 10px;'><b>Photo:</b></div>");
                var image = $("<div style='margin-top: 10px;'></div>");
                //var imgurl = './assets/images/' + datarecord.firstname.toLowerCase() + '.png';
                var imgurl = './assets/images/photo.png';
                var img = $('<img height="60" src="' + imgurl + '"/>');
                image.append(img);
                image.appendTo(photo);
                photocolumn.append(photo);

                var nip = "<div style='margin: 10px;'><b>NIP:</b> " + datarecord.person_code + "</div>";
                var nama = "<div style='margin: 10px;'><b>Nama:</b> " + datarecord.person_name + "</div>";
                var telp = "<div style='margin: 10px;'><b>Telp:</b> " + datarecord.person_telp + "</div>";
                var hp = "<div style='margin: 10px;'><b>HP:</b> " + datarecord.person_hp + "</div>";
                $(leftcolumn).append(nip);
                $(leftcolumn).append(nama);
                $(leftcolumn).append(telp);
                $(leftcolumn).append(hp);

                var alamat = "<div style='margin: 10px;'><b>Alamat:</b> " + datarecord.person_address + "</div>";
                var email = "<div style='margin: 10px;'><b>Email:</b> " + datarecord.person_email + "</div>";
                //var phone = "<div style='margin: 10px;'><b>Phone:</b> " + datarecord.homephone + "</div>";
                //var hiredate = "<div style='margin: 10px;'><b>Hire Date:</b> " + datarecord.hiredate + "</div>";

                $(rightcolumn).append(alamat);
                $(rightcolumn).append(email);
                //$(rightcolumn).append(phone);
                //$(rightcolumn).append(hiredate);

                //var notescontainer = $('<div style="white-space: normal; margin: 5px;"><span>' + datarecord.notes + '</span></div>');
                //$(notes).append(notescontainer);
                $(tabsdiv).jqxTabs({ width: 600, height: 170, theme: theme });
            }
        }

		// set rows details.
        $("#jqxgrid").bind('bindingcomplete', function (event) {
            if (event.target.id == "jqxgrid") {
                $("#jqxgrid").jqxGrid('beginupdate');
                var datainformation = $("#jqxgrid").jqxGrid('getdatainformation');
                var rows = $("#jqxgrid").jqxGrid('getrows');
                for (i = 0; i < datainformation.rowscount; i++) {
                    var hidden = i > 0 ? true : false;
                    //$("#jqxgrid").jqxGrid('setrowdetails', i, "<div id='grid" + i + "' style='margin: 10px;'></div>", 220, hidden);
                    $("#jqxgrid").jqxGrid('setrowdetails', i, 
                    	"<div class='tabs"+i+"' style='margin: 10px; white-space:normal;'>"+
                            "<ul style='margin-left: 30px;'>"+
                            	"<li>"+rows[i].person_code+"</li>"+
                            "</ul>"+
                            "<div class='information"+i+"'></div>"+
                   		"</div>", 220, true);
                }
                $("#jqxgrid").jqxGrid('resumeupdate');
            }
        });
		

		$("#jqxgrid").jqxGrid(
		{
			width: '100%',
			source: dataAdapter,
			theme: theme,
			sortable: true,
            pageable: true,
            autoheight: true,
            //rowdetails: true,
            //initrowdetails: initrowdetails,
			columns: [
				{ text: 'NAMA GROUP', dataField: 'group_name', width: 180 },
				{ text: 'KETERANGAN', dataField: 'group_desc', width: 180 },
				{ text: 'AKTIF', dataField: 'group_active', width: 100 },
				{ text: 'Edit', datafield: 'Edit', width: 125, columntype: 'button', cellsrenderer: function () {
					return "Edit";
				}, buttonclick: function (row) {
					// open form Create/Update.
					editrow = row;
					
					// get the clicked row's data and initialize the input fields.
					var dataRecord = $("#jqxgrid").jqxGrid('getrowdata', editrow);
					cu_formSet(dataRecord);
				}
				}
			]
		});

		//source jqxGridHakAkses
		var datafieldsHakAkses = [
			{name: 'menu_id'},
        	{name: 'menu_parent'},
        	{name: 'menu_position'},
        	{name: 'menu_title'},
        	{name: 'perm_create', type: 'bool'},
        	{name: 'perm_update', type: 'bool'},
        	{name: 'perm_read', type: 'bool'},
        	{name: 'perm_delete', type: 'bool'}
      	];
		var sourceHakAkses =
		{
			datatype: "json",
			datafields: datafieldsHakAkses,
			id: 'menu_id',
			url: 'index.php?c=c_group&m=get_permission',
			root: 'data',
			updaterow: function (rowid, rowdata) {
				if(rowdata.menu_parent == 0){
					var cell = $('#jqxGridHakAkses').jqxGrid('getselectedcell');
					$('#jqxGridHakAkses').jqxGrid('beginupdate');
					$("#jqxGridHakAkses").jqxGrid('setcellvalue', rowid, cell.datafield, true);
					$('#jqxGridHakAkses').jqxGrid('endupdate');
				}
				
			}
		};

		$("#jqxGridHakAkses").jqxGrid(
		{
			width: '100%',
			//source: dataAdapterHakAkses,
			theme: theme,
			editable: true,
			sortable: true,
            pageable: true,
            autoheight: true,
			selectionmode: 'singlecell',
			columns: [
				{ text: '#', dataField: 'menu_id', width: 100 },
				{ text: 'NAMA MENU', dataField: 'menu_title', width: 300 },
				{ text: 'AKSES', dataField: 'perm_read', width: 60, columntype: 'checkbox'/*, cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
	                console.log(columnproperties.cellsalign);
	            }*/ }
			]
		});
		/*$("#jqxGridHakAkses").bind('cellendedit', function (event) {
            var args = event.args;
            //$("#cellendeditevent").html("Event Type: cellendedit, Column: " + args.datafield + ", Row: " + (1 + args.rowindex) + ", Value: " + args.value);
            //console.log("Column = "+args.datafield);
            //console.log("Row = "+(1 + args.rowindex));
            //console.log("Value = "+args.value);
            //var rows = $('#jqxGridHakAkses').jqxGrid('getrows');
            //console.log(rows);
        });*/
		/* END DATA */

		/* START FORM */
		//initialize field
		$('.text-input').addClass('jqx-input');
		$('.text-input').addClass('jqx-rc-all');
		$('.text-input').width(200);
		$('.text-input').height(23);
		if (theme.length > 0) {
			$('.text-input').addClass('jqx-input-' + theme);
			$('.text-input').addClass('jqx-widget-content-' + theme);
			$('.text-input').addClass('jqx-rc-all-' + theme);
		}
		
		var textfield_groupid = $("#group_id");
		var textfield_groupname = $("#group_name");
		var textfield_groupdesc = $("#group_desc");
		textfield_groupdesc.height(48);
		textfield_groupdesc.bind('keypress', function(e) {
      		if ((e.keyCode || e.which) == 13) {
        	    return false;
       		}
      	});
		
		var radiofield_aktifyes = $("#jqxRadioBtnYes");
		var radiofield_aktifno = $("#jqxRadioBtnNo");
		
        radiofield_aktifyes.jqxRadioButton({ width: 50, height: 25, checked: true, theme: theme });
        radiofield_aktifno.jqxRadioButton({ width: 50, height: 25, checked: false, theme: theme });
		
		var date = new Date();
        var currentYear = date.getFullYear();
		var currentMonth = date.getMonth();
        var nextYear = currentYear+1;
        var thnAjaran = currentYear+"/"+nextYear;
        date.setFullYear(currentYear, currentMonth, 1);
		
		// initialize the popup window and buttons.
		$("#createBtn").jqxButton({ theme: theme });
		$("#Save").jqxButton({ theme: theme });
		$("#Cancel").jqxButton({ theme: theme });
        /* END FORM */
		
		/* START ACTION */
        // update the edited row when the user clicks the 'Save' button.
        $("#Save").click(function () {
			var group_id_field = "";
        	var group_name_field = "";
        	var group_desc_field = "";
        	var group_active_field = "";
        	
			if(textfield_groupid.val() !== null || textfield_groupid.val() !== ''){
				group_id_field = textfield_groupid.val();
			}
			if(textfield_groupname.val() !== null || textfield_groupname.val() !== ''){
				group_name_field = textfield_groupname.val();
			}
			if(textfield_groupdesc.val() !== null || textfield_groupdesc.val() !== ''){
				group_desc_field = textfield_groupdesc.val();
			}
			if(radiofield_aktifyes.jqxRadioButton('checked') == true){
				group_active_field = "Y";
			}else{
				group_active_field = "T";
			}

			var rows_hak = $("#jqxGridHakAkses").jqxGrid('getrows');
        	var rowscount_hak = $("#jqxGridHakAkses").jqxGrid('getdatainformation').rowscount;

        	var perm_menu = [];
        	var menu_parent = [];

        	for(var i=0; i<rowscount_hak; i++){
            	if(rows_hak[i].perm_read == true){
            		perm_menu.push(rows_hak[i].menu_id);
            		menu_parent.push(rows_hak[i].menu_parent);
            	}
        	}
        	
        	var row = {
                	task: group_task,
					group_id: group_id_field,
                	group_name: group_name_field,
            		group_desc: group_desc_field,
					group_active: group_active_field,
					'perm_menu[]': perm_menu,
					'menu_parent[]': menu_parent
        	};

        	//console.log(radiofield_aktifyes.jqxRadioButton('checked'));

        	/*console.log(rows_title);

        	$.ajax({
                type: 'POST',
                url: 'index.php?c=c_group&m=create',
                data: {'title[]': rows_title},
                success: function(response){
                    console.log('sukses');
                }
            });*/
        	
        	
        	
            if (editrow >= 0) {
                //edit row
            	$.ajax({
                    type: 'POST',
                    url: 'index.php?c=c_group&m=get_action',
                    data: row,
                    success: function(response){
                        //if(response==1){
                            $('#jqxgrid').jqxGrid('updatebounddata');
                            gridExpand();
                        //}
                    }
                });
            }else{
            	//add row
            	$.ajax({
                    type: 'POST',
                    url: 'index.php?c=c_group&m=get_action',
                    data: row,
                    success: function(response){
                        if(response==1){
                            $('#jqxgrid').jqxGrid('updatebounddata');
                            gridExpand();
                        }
                    }
                });
            	
            }
        });

        $("#Cancel").click(function () {
        	cu_formReset();
        	$("#popupWindow").jqxWindow('hide');
        	gridExpand();
        });
		
		$("#createBtn").click(function () {
        	btn_group_task = "CREATE";

        	cu_formReset();
			
    		var dataAdapterHakAkses = new $.jqx.dataAdapter(sourceHakAkses);
    		$("#jqxGridHakAkses").jqxGrid({source: dataAdapterHakAkses});
    		
        	formExpand();
        	
        	textfield_groupid.val(0);
        });
        
        /* END ACTION */

        /* START FUNCTION */
		function cu_formReset(){
			textfield_groupid.val(0);
			textfield_groupname.val("");
			textfield_groupdesc.val("");
			radiofield_aktifyes.jqxRadioButton({ checked: true });
        }

        function cu_formSet(dataRecord){
            btn_group_task = "UPDATE";
			
			/*var arr_tglrevisi = dataRecord.TGLREVISI.split('-');
			var thn = arr_tglrevisi[0];
			var bln = arr_tglrevisi[1];
			var tgl = arr_tglrevisi[2];
			var set_tglrevisi = new Date(thn, (bln - 1), tgl);*/
			
			textfield_groupid.val(dataRecord.group_id);
			textfield_groupname.val(dataRecord.group_name);
			textfield_groupdesc.val(dataRecord.group_desc);
			if(dataRecord.group_active == 'Y'){
				radiofield_aktifyes.jqxRadioButton({ checked: true });
				radiofield_aktifno.jqxRadioButton({ checked: false });
			}else{
				radiofield_aktifyes.jqxRadioButton({ checked: false });
				radiofield_aktifno.jqxRadioButton({ checked: true });
			}

			var sourceHakAksesByGroup =
			{
				datatype: "json",
				datafields: datafieldsHakAkses,
				id: 'menu_id',
				url: 'index.php?c=c_group&m=get_permission_bygroup',
				data: {group_id: dataRecord.group_id},
				root: 'data',
				updaterow: function (rowid, rowdata) {
					if(rowdata.menu_parent == 0){
						var cell = $('#jqxGridHakAkses').jqxGrid('getselectedcell');
						$('#jqxGridHakAkses').jqxGrid('beginupdate');
						$("#jqxGridHakAkses").jqxGrid('setcellvalue', rowid, cell.datafield, true);
						$('#jqxGridHakAkses').jqxGrid('endupdate');
					}
					
				}
			};
			$("#jqxGridHakAkses").jqxGrid({source: sourceHakAksesByGroup});
            
            formExpand();
        }
		
        function gridExpand(){
			gridExpandVar = 1;
			formExpandVar = 0;
        	navbar.jqxNavigationBar('expandAt', 0);
        }
        function formExpand(){
			gridExpandVar = 0;
			formExpandVar = 1;
        	navbar.jqxNavigationBar('expandAt', 1);
        }
        /* END FUNCTION */
		
		navbar.bind('expandedItem', function (event) {
			if((event.item == 1) && (formExpandVar == 1) && (btn_group_task == "UPDATE")){
				group_task = "UPDATE";
			}else{
				group_task = "CREATE";
			}
		});
		
		navbar.jqxNavigationBar('expandAt', 0);
		navbar.jqxNavigationBar('collapseAt', 1);

	});
</script>

<style type="text/css">
    .text-input
    {
        height: 21px;
        width: 150px;
    }
    .register-table
    {
    	width: 468px;
        margin-top: 10px;
        margin-bottom: 10px;
    }
    .register-table td, tr
    {
        margin: 0px;
        padding: 2px;
        border-spacing: 0px;
        border-collapse: collapse;
        font-family: Verdana;
        font-size: 12px;
    }
    h3 
    {
        display: inline-block;
        margin: 0px;
    }
    textarea
	{
	   resize: none;
	   font-family: Verdana;
	   font-size: 12px;
	}
</style>

<div id='jqxNavigationBar'>
	<!--Header-->
	<div>Data</div>
	<!--Content-->
	<div>
		<div id="jqxgrid"></div>
	</div>
	<!--Header-->
	<div>Form Create/Update</div>
	<!--Content-->
	<div>
		<form id="groupForm" action="#">
		<table class="register-table">
			<tr style="display: none;">
				<td align="right">GROUP ID:</td>
				<td align="left"><input id="group_id" class="text-input" /></td>
			</tr>
			<tr>
				<td align="right" valign="top" width="120px">NAMA GROUP:</td>
				<td align="left"><input id="group_name" class="text-input" /></td>
			</tr>
			<tr>
				<td align="right" valign="top">KETERANGAN:</td>
				<td align="left"><textarea id="group_desc" cols="49" rows="5" class="text-input" ></textarea></td>
			</tr>
			<tr>
				<td align="right" valign="top">AKTIF:</td>
				<td align="left" valign="top"><div style="float: left; vertical-align: middle;" id='jqxRadioBtnYes'>Ya</div><div style="float: left;" id='jqxRadioBtnNo'>Tidak</div></td>
			</tr>
			<!-- <tr>
				<td align="right">SEMUA AKSES ?:</td>
				<td align="left"><input id="group_kodejab" /></td>
			</tr>-->
			<tr>
				<td colspan="2"><div id="jqxGridHakAkses"></div></td>
			</tr>
			<tr>
				<td align="right"></td>
				<td style="padding-top: 10px;" align="right"><input style="margin-right: 5px;" type="button" id="Save" value="Save" /><input id="Cancel" type="button" value="Cancel" /></td>
			</tr>
		</table>
		</form>
	</div>
</div>

<div style="margin-top: 10px;">
	<input id="createBtn" type="button" value="Create Data" />
</div>
